<?php

namespace app\sys\service;

use think\admin\Exception;
use think\admin\Service;
use think\admin\service\InterfaceService;

class syncService extends Service
{
    /**
     * 同步所有数据
     * @param string $uri
     * @param int $pageSize
     * @return array
     * @throws Exception
     */
    public static function syncAllData(string $uri, int $pageSize): array
    {
        $page = 1;
        $allData = [];
        do {
            $response = self::syncData($uri, $page, $pageSize);
            if (empty($response['data']['list'])) {
                break; // 如果返回的数据为空数组，表示数据已同步完，结束循环
            }
            array_push($allData, ...$response['data']['list']);
            $page++;
            usleep(500000); // 500ms 的延迟
        } while (true);

        return $allData;
    }

    /**
     * 同步橙石开放平台数据
     * @param string $uri
     * @param int|null $page
     * @param int|null $pageSize
     * @return array
     * @throws Exception
     */
    public static function syncData(string $uri, ?int $page = null, ?int $pageSize = null): array
    {
        $params = self::getAppParams();

        if ($page !== null && $pageSize !== null) {
            $p['page'] = $page;
            $p['pageSize'] = $pageSize;
            $uri = $uri.'?'.http_build_query($p);
        }

        return static::getInterface()->doRequest($uri, $params);
    }


    /**
     * 获取橙石开放平台接口实例
     * @return InterfaceService
     * @throws Exception
     */
    private static function getInterface(): InterfaceService
    {
        $service = InterfaceService::instance();
        $service->getway(sysconfig('TRUTHFUL', 'SQM_TRUTHFUL_GATEWAY'));
        $service->setAuth(sysconfig('TRUTHFUL', 'SQM_TRUTHFUL_APP_ID'), sysconfig('TRUTHFUL', 'SQM_TRUTHFUL_APP_KEY'));
        return $service;
    }

    /**
     * @return array
     * @throws Exception
     */
    private static function getAppParams(): array
    {
        return ['app_id' => sysconfig('TRUTHFUL', 'SQM_TRUTHFUL_APP_ID'), 'app_key' => sysconfig('TRUTHFUL', 'SQM_TRUTHFUL_APP_KEY')];
    }
}